const moment = require('moment')

class DateUtils {
  getAge(birthday, time = new moment()) {
    if ((typeof birthday) === "string") {
      birthday = new moment(birthday, "YYYY-MM-DD")
    } else if (moment.isDate(birthday)) {
      birthday = moment(birthday)
    }

    if ((typeof time) === "string") {
      time = new moment(time, "YYYY-MM-DD HH:mm:ss")
    } else if (moment.isDate(time)) {
      time = moment(time)
    }
    return time.year() - birthday.year()
  }
  // 获取具体年龄（年，月，日，月龄）
  getDateAge(timestamp) {
    let date = new Date()
    let now = {
      year: date.getFullYear(),
      month: date.getMonth(),
      date: date.getDate()
    }
    date = new Date(timestamp * 1000)
    let birth = {
      year: date.getFullYear(),
      month: date.getMonth(),
      date: date.getDate()
    }

    let day = now.date - birth.date
    let month = now.month - birth.month
    let year = now.year - birth.year
    // 出生月份的天数
    let birth_month_days = (+new Date(birth.year, birth.month + 1, 1) - new Date(birth.year, birth.month, 1)) / (1000 * 24 * 60 * 60)

    day < 0 && month--
    month < 0 && year--
    month < 0 && (month = 12 + month)

    day < 0 && (day = birth_month_days - birth.date + now.date)
    return {
      year,
      month: month+1,
      months: year * 12 + month, // 月龄
      date: day
    }
  }

}

export default new DateUtils()



// WEBPACK FOOTER //
// ./src/utils/DateUtils.js
